<?php

namespace Payment\Notify;

use Payment\Common\PayException;
use Payment\Common\HsqConfig;
use Payment\Config;
use Payment\Utils\ArrayUtil;
use Payment\Utils\StrUtil;


/**
 * Class MiNotify
 * 微信回调处理
 * @package Payment\Notify
 * @anthor yeran
 */
class HsqNotify extends NotifyStrategy
{

    /**
     * MiNotify constructor.
     * @param array $config
     * @throws PayException
     */
    public function __construct(array $config)
    {
        parent::__construct($config);

        try {
            $this->config = new HsqConfig($config);
        } catch (PayException $e) {
            throw $e;
        }
    }

    /**
     * 获取返回的异步通知数据
     * @return array|bool
     * @author yeran
     */
    public function getNotifyData()
    {
        //支持直接读取input流
        $data = $_POST['req'] ?? file_get_contents('php://input');
        if(empty($data)){//如果参数为空,则不进行处理
            return false;
        }
        $tmp = explode("&",urldecode($data));
        $new_data = array();
        foreach($tmp as $val)
        {
            $tmp2 = explode("=",$val);
            $new_data[$tmp2[0]] = $tmp2[1];
        }
        return $new_data;
    }

    /**
     * 检查异步通知的数据是否正确
     * @param array $data
     *
     * @author yeran
     * @return boolean
     */
    public function checkNotifyData(array $data)
    {
        // 检查返回数据签名是否正确
        return $this->verifySign($data);
    }

    /**
     * 检查微信返回的数据是否被篡改过
     * @param array $retData
     * @return boolean
     * @author yeran
     */
    protected function verifySign(array $retData)
    {
        if (empty($this->config->key)) return false;
        if (empty($this->config->publicKey)) return false;

        $key = $this->config->key;
        $publicKey = $this->config->publicKey;

        if(is_file($publicKey))
        {
            $publicKey = openssl_get_publickey(file_get_contents($publicKey));
        }
        else
        {
            $publicKey = $this->config->publicKey;
        }
        if (empty($publicKey)) return false;

        $sign = $retData['sign'];

        //固定格式拼接后
        $signArr = [
            'method' => $retData['method'],
            'version' => $retData['version'],
            'format' => $retData['format'],
            'merchantNo' => $retData['merchantNo'],
            'signType' => $retData['signType'],
            'signContent' => $retData['signContent'],
            'key' => $key,
        ];
        $signStr = ArrayUtil::createLinkstring($signArr);
        //验签
        $result = openssl_verify($signStr,hex2bin($sign), $publicKey, OPENSSL_ALGO_SHA256);
        if($result)
        {
           return true; //验签成功
        }
        else
        {
            return false;
        }
    }

    /**
     *
     * 封装回调函数需要的数据格式
     *
     * @param array $data
     *
     * @return array
     * @author yeran
     */
    protected function getRetData(array $params)
    {
        $data = json_decode($params['signContent'],true);
//        Array
//        (
//            [buyerName] => oAFzv5a67bJ0aGk7cB-RfK0Yap8s //openid
//            [channelOrderNo] => 23051714261110391231100016376946 //请求渠道商户订单号
//            [finishedDate] => 20230517142648
//            [fundBankCode] => OTHERS
//            [fundChannel] => OTHERS
//            [goodsInfo] => 【猎电新能源】微信充值
//            [memo] => {"openid":"oAFzv5a67bJ0aGk7cB-RfK0Yap8s","appid":"wxfbe753bb28212636","latitude":"22.33","spbillCreateIp":"150.158.53.11","paylimit":"no_credit","longitude":"171.21"}
//            [orderAmt] => 3000
//            [orderStatus] => SUCCESS
//            [payOrderNo] => 4200001872202305170697281261 //渠道交易单号(支付宝/微信/银联返回的交易号)
//            [payType] => WECHAT_APPLET
//            [requestDate] => 20230517142644
//            [respCode] => 000000
//            [respMsg] => 交易成功
//            [tradeNo] => 25000020230420100923003888927786 //交易订单号(慧收钱系统交易订单号)
//            [transNo] => 20230517142644095535524955535120 //商户订单号(原支付交易对应的商户订单号)
//        )
        $retData = [
            'openid' => $data['buyerName'],
            'order_no' => $data['transNo'],
            'transaction_id' => $data['tradeNo'],
            'amount' => $data['orderAmt'],
            'outtrxid' => $data['channelOrderNo'],
            'chnltrxid'=> $data['payOrderNo'],
            'channel' => Config::HSQ_CHARGE,
        ];
        return $retData;
    }

    /**
     * 处理完后返回的数据格式
     * @param bool $flag
     * @param string $msg 通知信息，错误原因
     * @author yeran
     * @return string
     */
    protected function replyNotify($flag, $msg = 'OK')
    {
        // 默认为成功
        $return_code ='SUCCESS';
        if (!$flag) {
            $return_code ='FAIL';
        }
        return $return_code;
    }
}
